<template>
  <div class="prod-add" :class="{ 'searching' : state.type === 'search' }">
    <div class="prod-nav">
      <!--  -->
      <van-nav-bar title="添加商品" @click-left="toRouter('back')">
        <template #left><van-icon name="arrow-left" size="18" color="#333" /></template>
      </van-nav-bar>
      <!--  -->
      <form action="/">
        <van-search
          v-model="state.searchValue"
          show-action
          :clearable="false"
          placeholder="请输入商品名称"
          @search="onSearch"
        >
          <template #action>
            <div v-show="state.searchValue" @click="onCancel">取消</div>
          </template>
        </van-search>
      </form>
      <!--  -->
      <van-tabs v-model:active="nav.current" color="#FE2E4E" @click="changeNav" v-show="state.type !== 'search'">
        <van-tab v-for="(item, index) in nav.list" :key="index" :name="item.type" :title="item.title"></van-tab>
      </van-tabs>
    </div>
    <!-- 推荐 -->
    <div class="recommended-prod" v-show="state.type === 'product'">
      <h3>推荐</h3>
      <div class="recommended-list">
        <div class="recommended-item" v-for="(item, index) in recommendList" :key="index" @click="toRouter({name: 'prodDetail', query: { pdId: item.pdId, userProductId: item.userProductId, admin: true }})">
          <van-image width="100" height="100" radius="8" :src="item.imageUrl"/>
          <div class="recommended-title">{{item.title}}</div>
          <div class="recommended-price"><span>赚{{item.ratePrice}}</span><span class="clr-red">￥{{item.price}}</span></div>
          <van-button
            size="mini"
            :type="Number(item.onSale) ? 'danger':'default'"
            :plain="!Number(item.onSale)"
            :color="Number(item.onSale) ? '#FE2E4E':''"
            @click.stop="handleSale(item, index, 'recommended')"
          >
            {{Number(item.onSale) ? '移出橱窗':'加橱窗'}}
          </van-button>
        </div>
      </div>
    </div>
    <!-- 分类 -->
    <div class="prod-tab" v-show="state.type === 'product'">
      <van-tabs class="prod-tab-list" :class="{'fixed': tabFixed}" color="#FE2E4E" @click="changeCategory">
        <van-tab v-for="(item, index) in category.list" :key="index" :title="item.title"></van-tab>
      </van-tabs>
    </div>
    <!-- 产品列表 -->
    <van-list
      class="prod-list"
      v-model:loading="state.loading"
      :finished="state.finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-card :thumb="item.imageUrl" v-for="(item, index) in state.list" :key="index" @click="toRouter({name: 'prodDetail', query: { pdId: item.pdId, userProductId: item.userProductId, admin: true }})">
        <template #title>
          <div class="prod-title">
            <h2 class="van-multi-ellipsis--l2">{{item.title}}</h2>
            <van-icon name="star" :color="Number(item.isFaveriate) ? '#FE2E4E':'#999'" @click.stop="handleFaveriate(item, index)" />
          </div>
        </template>
        <template #price>
          <p class="van-card__desc van-ellipsis">赚￥{{item.ratePrice}}</p>
          <div class="prod-price">价格：<strong class="clr-red">￥{{item.price}}</strong></div>
          <van-button class="edit-btn" size="small"
            :type="Number(item.onSale)?'danger':'default'"
            round
            plain
            @click.stop="handleSale(item, index)"
          >
            {{Number(item.onSale)?'移出橱窗':'加橱窗'}}
          </van-button>
        </template>
      </van-card>
    </van-list>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  getRecommendProductList,
  getSYSCategoryList,
  getProductListBySYSCategory,
  getMyFavoriteProList,
  postFaveriate,
  searchProduct,
  addProductToMyShop,
  delProductInMyShop
} from '@api'

// 商品 用户收藏
const handleNav = (state, onLoad) => {
  const nav = reactive({
    current: 'product',
    list: [
      { title: '商品', type: 'product' },
      { title: '用户收藏', type: 'favorite' }
    ]
  })
  const changeNav = (type) => {
    state.list = []
    state.pageNum = 0
    state.type = type
    onLoad()
  }
  return { nav, changeNav }
}

// 推荐列表
const recommend = () => {
  const recommendList = reactive([])
  getRecommendProductList().then(res => {
    const { content } = res
    recommendList.push(...content)
  })
  return { recommendList }
}

// 分类
const handleCategory = (state, onLoad) => {
  const category = reactive({
    list: [{ id: '', title: '全部分类' }]
  })
  getSYSCategoryList().then(res => {
    const { content } = res
    category.list.push(...content)
  })
  const changeCategory = (index) => {
    state.list = []
    state.pageNum = 0
    state.categoryId = category.list[index].id
    onLoad()
  }
  const tabFixed = ref(false)
  const scrollHandle = () => {
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    var tabTop = document.querySelector('.prod-list').offsetTop
    tabFixed.value = scrollTop + 188 >= tabTop
  }
  onMounted(() => {
    window.addEventListener('scroll', scrollHandle)
  })
  onUnmounted(() => {
    window.removeEventListener('scroll', scrollHandle)
  })
  return { category, changeCategory, tabFixed }
}

// 列表
const product = () => {
  const state = reactive({
    list: [],
    loading: false,
    finished: false,
    pageNum: 0,
    categoryId: '',
    searchValue: '',
    type: 'product'
  })
  // 加载列表
  const onLoad = async () => {
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    })
    const { pageNum, categoryId, searchValue: proTitle } = state
    var res
    switch (state.type) {
      case 'favorite':
        res = await getMyFavoriteProList({ pageNum })
        break
      case 'search':
        res = await searchProduct({ pageNum, proTitle })
        break
      default:
        res = await getProductListBySYSCategory({ pageNum, categoryId })
    }
    const { content, pageNo, totalPages } = res.content
    state.list = state.list.concat(content)
    state.pageNum = pageNo + 1
    state.loading = false
    Toast.clear()
    if (pageNo + 1 >= totalPages) {
      state.finished = true
    } else {
      state.finished = false
    }
  }
  // 收藏
  const handleFaveriate = (item, index) => {
    const { pdId, isFaveriate } = item
    const url = Number(isFaveriate) ? 'dislike' : 'save'
    postFaveriate(url, {
      objectId: pdId
    }).then(res => {
      if (state.type !== 'favorite') { // 商品列表 搜索列表
        state.list[index].isFaveriate = Number(isFaveriate) ? '0' : '1'
      } else { // 收藏列表
        state.list.splice(index, 1)
      }
    })
  }
  return { state, onLoad, handleFaveriate }
}

const handleSearch = (state, onLoad, nav) => {
  const onSearch = (val) => {
    state.list = []
    state.pageNum = 0
    state.type = 'search'
    onLoad()
  }
  const onCancel = () => {
    state.list = []
    state.pageNum = 0
    state.searchValue = ''
    state.type = 'product'
    nav.current = 'product'
    onLoad()
  }
  return { onSearch, onCancel }
}

export default {
  name: 'prodAdd',
  setup () {
    const router = useRouter()
    const toRouter = (path) => {
      path === 'back' ? router.go(-1) : router.push(path)
    }

    const { state, onLoad, handleFaveriate } = product()
    const { recommendList } = recommend()
    const { nav, changeNav } = handleNav(state, onLoad)
    const { category, changeCategory, tabFixed } = handleCategory(state, onLoad)
    const { onSearch, onCancel } = handleSearch(state, onLoad, nav)

    // 上下架
    const handleSale = async (item, index, type) => {
      const { pdId, categoryId, onSale } = item
      Number(onSale)
        ? await delProductInMyShop({ pdIds: pdId })
        : await addProductToMyShop({ pdId, categoryId })
      if (type === 'recommended') {
        recommendList[index].onSale = Number(onSale) ? '0' : '1'
      } else {
        state.list[index].onSale = Number(onSale) ? '0' : '1'
      }
    }

    return {
      toRouter,
      nav,
      changeNav,
      recommendList,
      category,
      changeCategory,
      tabFixed,
      state,
      onLoad,
      handleFaveriate,
      handleSale,
      onSearch,
      onCancel
    }
  }
}
</script>

<style scoped lang="scss">
@import './prodAdd.scss';
</style>
